package pers.liyan.shi.springclouddistributedlocker.redis;

import org.apache.commons.lang3.BooleanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * redis分布式锁
 * @author ShiLY
 * @version 1.0
 * @date 2020/2/23 15:46
 */
@Component
public class RedisLocker {

    private final StringRedisTemplate redisTemplate;

    public RedisLocker(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * 获取锁
     * @param key key
     * @param value value
     * @param timeout 超时时间
     * @param timeUnit 时间单位
     */
    public boolean acquire(String key, String value, int timeout, TimeUnit timeUnit) {

        Boolean setIfAbsent = redisTemplate.opsForValue()
                .setIfAbsent(key, value, timeout, timeUnit);

        if (BooleanUtils.isTrue(setIfAbsent)) {
            String s = redisTemplate.opsForValue().get(key);
            return Objects.equals(s, value);
        }

        return false;
    }

    /**
     * 释放锁
     * @param key key
     * @param value value
     */
    public void release(String key, String value) {


        String s = redisTemplate.opsForValue()
                .get(key);
        if (Objects.equals(value, s)) {
            redisTemplate.delete(key);
        }
    }


}
